<?php
final class HtmlCache {
    public function __construct() {
        $files = glob(DIR_CACHE . 'hc/cache.*');

        if ($files) {
            foreach ($files as $file) {
                if($separator=strrchr($file, '_')){
                    $time = substr($separator, 1);

                    if ($time < time()) {
                        if (file_exists($file)) {
                            unlink($file);
                        }
                    }
                }
            }
        }
    }

    public function get($key) {
        if(!($files = glob(DIR_CACHE . 'hc/cache.' . preg_replace('/[^A-Z0-9\._-]/i', '', $key)))){
            $files = glob(DIR_CACHE . 'hc/cache.' . preg_replace('/[^A-Z0-9\._-]/i', '', $key) . '_*');
        }

        if ($files) {
            $cache = file_get_contents($files[0]);

            return unserialize($cache);
        }

        return FALSE;
    }

    public function set($key, $value, $autoClear=FALSE, $expire = 3600) {
        $this->delete($key);

        if($autoClear){
            $file = DIR_CACHE . 'sc/cache.' . preg_replace('/[^A-Z0-9\._-]/i', '', $key) . '_' . (time() + $expire);
        }else{
            $file = DIR_CACHE . 'sc/cache.' . preg_replace('/[^A-Z0-9\._-]/i', '', $key);
        }

        if($handle = fopen($file, 'w')){
            if(flock($handle, LOCK_EX | LOCK_NB)){
                fwrite($handle, serialize($value));

                flock($handle, LOCK_UN);
            }
            fclose($handle);
        }
    }

    public function delete($key) {
        $files = glob(DIR_CACHE . 'sc/cache.' . preg_replace('/[^A-Z0-9\._-]/i', '', $key) . '*');

        if ($files) {
            foreach ($files as $file) {
                if (file_exists($file)) {
                    unlink($file);
                }
            }
        }
    }
}
?>